package com.jci.xyf.hellofx.oil;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.jci.xyf.hellofx.mysqlconn;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;

import java.sql.ResultSet;
import java.sql.SQLException;

public class Controller1 {
    public Label today;
    //public ImageView logo;
    @FXML
    private Label cinemas;
    @FXML
    private TextField soTxt;
//    @FXML
//    private ImageView photo;
    @FXML
    protected void oilselect() {
        //起到一个Loading的效果
        cinemas.setText("Loading……");
        String position = soTxt.getText();
        mysqlconn my = new mysqlconn();
        my.startmysql();
        //异步机制
        Platform.runLater(new Runnable() {
        @Override
        public void run() {
        String url = "https://qqlykm.cn/api/oilprice/get?key=UzU1uxxMaQXeR4R87HRKYT63Cv&name=" + position;
        String result = HttpUtil.get(url);
            System.out.println(result);
        result = ("{"+result.substring(result.indexOf("p0")-1,result.indexOf("update_time")-1));
            System.out.println(result);
        oilData oil = JSONUtil.toBean(result, oilData.class);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String sqlexit = "SELECT *\n" + "FROM oil\n" + "WHERE position='" + position + "';";
        ResultSet rs = my.query(sqlexit);
        try {
            if (rs.next() == false) {
                //haibao.setText("今日油价" + "\n");
                //Image image = new Image(video.getImage_url());
                //photo.setImage(image);
                String out = "P0：" + oil.getP0() + "\n";
                out += "P92：" + oil.getP92() + "\n";
                out += "P89：" + oil.getP89() + "\n";
                out += "P95：" + oil.getP95() + "\n";
                cinemas.setText(out);
                String sql = "insert into oil(P0,P92,P89,P95,position) values('"+oil.getP0()+"','"+oil.getP92()+"','"+oil.getP89()+"','"+oil.getP95()+"','"+position+"')";
                my.updata(sql);
            } else {
                //haibao.setText("今日油价" + "\n");
                //Image image = new Image(rs.getString("影视海报"));
                //photo.setImage(image);
               // cinemas.setText("今日"+position+"油价");
                today.setText(position+"今日油价");
                String out = "P0：" + rs.getString("P0") + "\n";
                out += "P92：" + rs.getString("P92") + "\n";
                out += "P89：" + rs.getString("P89") + "\n";
                out += "P95：" + rs.getString("P95") + "\n";
                cinemas.setText(out);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
    });
    }
}

